package com.skywork.domain;

import java.util.Date;

import javax.persistence.Table;
import javax.persistence.Transient;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.skywork.domain.base.ActiveFlag;
import com.skywork.domain.base.IdEntity;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
 * 
 * @author juwu
 *
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper=true)
@Table(schema = "cfg", name = "access_token")
public class AccessToken extends IdEntity {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Long channelId;

	private String token;

	@Transient
	private Long expiresDate;

	private Long expiresIn;

	public AccessToken(long channelId, String randomAlphanumeric, Long expiresIn) {
		this.createDate = new Date();
		this.channelId = channelId;
		this.token = randomAlphanumeric;
		this.expiresIn = expiresIn;
		this.activeFlag = ActiveFlag.ACTIVE;
		if (expiresIn != null) {
			this.expiresDate = System.currentTimeMillis() + ((expiresIn - 5) * 1000);
		}
	}

	
	public Long getExpiresDate() {
		return createDate.getTime() + ((expiresIn - 5) * 1000);
	}

	@Transient
	@JsonIgnore
	public boolean isAvailable() {
		Long expiresDate = getExpiresDate();
		if (expiresIn == null) {
			return true;
		}
		if (expiresDate == null) {
			return false;
		}
		if (expiresDate < System.currentTimeMillis()) {
			return false;
		}
		if (!activeFlag.equals(ActiveFlag.ACTIVE)) {
			return false;
		}
		return token != null;
	}

}
